<template>
  <div class="page sendMessage">
    <awesome-picker
      ref="pickerMember"
      colorTitle="#38ADFF"
      colorConfirm="#38ADFF"
      :textTitle="pickerMember.textTitle"
      :data="pickerMember.data"
      :anchor="pickerMember.anchor"
      @confirm="handlepickerMemberConfirm"
      class="pickerZindex"
    ></awesome-picker>
    <awesome-picker
      ref="pickerGender"
      colorTitle="#38ADFF"
      colorConfirm="#38ADFF"
      :textTitle="pickerGender.textTitle"
      :data="pickerGender.data"
      :anchor="pickerGender.anchor"
      @confirm="handlepickerGenderConfirm"
      class="pickerZindex"
    ></awesome-picker>
    <awesome-picker
      ref="pickerSign"
      colorTitle="#38ADFF"
      colorConfirm="#38ADFF"
      :textTitle="pickerSign.textTitle"
      :data="pickerSign.data"
      :anchor="pickerSign.anchor"
      @confirm="handlepickerSignConfirm"
      class="pickerZindex"
    ></awesome-picker>
    <StoreChoice
      ref="StoreChoice"
      :current="store"
      :multipleChoice="true"
      :multipleSelectAll="true"
      @listenToStoreSelect="getSelectStoreValue"
      :statusFilter="true"
      :hasTotal="true"
      :returnAllNull="true"
    />
    <mt-datetime-picker
      ref="dateTimePicker"
      type="dateTime"
      class="date-timer-picker"
      year-format="{value} 年"
      month-format="{value} 月"
      date-format="{value} 日"
      @confirm="confirmPicker"
      @cancel="cancelPicker"
      :startDate="startDate"
      :endDate="endDate"
      :startHour="startHour"
      :endHour="endHour"
    ></mt-datetime-picker>
    <div class="scroll-view">
      <customHeader
        middleTitle="发送短信"
        rightTitle="说明"
        @rightCallBack="openModal"
        @leftCallBack="handleBack"
      />
      <div class="page-body">
        <div class="top-tip" @click="()=>{this.topTip=false}" v-if="topTip">
          <i class="zhk-order_fa"></i>
          <i class="zhk-alert_close"></i>每日22:00至次日7:00为免打扰时间，将不会发送短信给消费者；未发短信不补发。
        </div>
        <div class="form-title">发送人群</div>
        <ul class="form-style">
          <li @click="handleClickSelectStore">
            <span>门店</span>
            <div>
              {{storeFormate()}}
              <i class="zhk-list_rarrow" v-if="roleInfo.manyShopFlag"></i>
            </div>
          </li>
          <li @click="showPicker('pickerMember')">
            <span>会员来源</span>
            <div class="pick-value">
              {{pickerMember.selected.text}}
              <i class="zhk-list_rarrow"></i>
            </div>
          </li>
          <li @click="showPicker('pickerGender')">
            <span>性别</span>
            <div class="pick-value">
              {{pickerGender.selected.text}}
              <i class="zhk-list_rarrow"></i>
            </div>
          </li>
          <li class="disabled">
            <span>触达人数</span>
            <div>{{memberCount}}</div>
          </li>
        </ul>
        <div class="form-title">短信内容</div>
        <div class="input-wrap">
          <textarea
            name
            id
            rows="3"
            placeholder="请输入短信内容,最多400个字"
            v-model="msgContent"
            maxlength="400"
          ></textarea>
          <div class="input-bottom">退订回T</div>
        </div>
        <div class="filed-tip">{{fieldTip}}</div>
        <ul class="form-style mb20">
          <li @click="showPicker('pickerSign')">
            <span>签名</span>
            <div class="pick-value">
              {{pickerSign.selected.text}}
              <i class="zhk-list_rarrow"></i>
            </div>
          </li>
        </ul>
        <ul class="form-style">
          <li>
            <span>定时发送</span>
            <div>
              <mt-switch v-model="switchValue"></mt-switch>
            </div>
          </li>
          <li v-show="switchValue" @click="openPicker">
            <span>时间</span>
            <div>
              {{formateDate(sendTime)}}
              <i class="zhk-list_rarrow"></i>
            </div>
          </li>
        </ul>
        <div class="btn-wrap">
          <div class="btn" @click="submit">提交</div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import Vue from "vue";
import customHeader from "../../components/header/header";
import StoreChoice from "../../components/StoreChoice/StoreChoice";
import { Toast, DatetimePicker, Popup, MessageBox, Switch } from "mint-ui";
import jsBridge from "../../tools/jsBridge.js";
import AwesomePicker from "vue-awesome-picker";
import moment from "moment";
Vue.component(DatetimePicker.name, DatetimePicker);
Vue.use(AwesomePicker);
Vue.component(Popup.name, Popup);
Vue.component(Switch.name, Switch);
export default {
  name: "sendMessage",
  data() {
    return {
      isOpenMember: false,//是否开通会员服务
      topTip: true,
      fieldTip: "总计：0个字",
      switchValue: false,
      memberCount: 0,//触达人数
      sendTime: new Date(new Date().getTime() + 60 * 60 * 1000),
      startDate: new Date(new Date().getTime() + 60 * 60 * 1000),
      endDate: new Date(new Date().getTime() + 7 * 24 * 60 * 60 * 1000),
      startHour: 8,
      endHour: 22,
      msgContent: "",
      roleInfo: {},
      detailsParams: null,
      store: [{ selectKey: "", selectName: "全部门店" }],
      pickerMember: {
        anchor: [],
        textTitle: "会员来源",
        selected: { text: "全部", value: "" },
        data: [{ value: "全部", id: "" }, { value: "支付宝", id: "1" }, { value: "微信", id: "2" }, { value: "线下导入", id: "3" }]
      },
      pickerGender: {
        anchor: [],
        textTitle: "性别",
        selected: { text: "全部", value: "" },
        data: [{ value: "全部", id: "" }, { value: "男", id: "1" }, { value: "女", id: "2" }, { value: "未知", id: "0" }]
      },
      pickerSign: {
        anchor: [],
        textTitle: "签名",
        selected: { text: "", value: "" },
        data: []
      },
      loadding: false,
    };
  },
  methods: {
    handleBack() {
      MessageBox({
        title: '提示',
        message: '确认离开当前页面吗？未保存的数据将会丢失！',
        showCancelButton: true,
      }).then(action => {
        if (action == "confirm") {
          if (String(this.$route.query.close) == "true") {
            jsBridge.closeWindow();
          } else {
            this.$router.back();
          }
        }
      });
    },
    storeFormate() {
      let v = "";
      if (this.store.length === 1) {
        v = this.store[0].selectName;
      } else if (this.store.length === 0) {
        v = "全部门店";
      } else {
        v = "已选" + this.store.length + "家门店";
      }
      return v;
    },
    //说明
    openModal() {
      MessageBox({
        title: '计费规则',
        message: '<div style="text-align:left;">• 短信字数<=70个字，按照70个字一条短信计算。中文英文符号统一计算为一个字符。<br />• 短信字数>70个字，占用3个字符作为分条字符，按照67个字记为一条短信计算，多条短信可能在部分手机系统上呈现为一条短信的形态，测试时请注意。<br />• 短信字数计算规则：短信内容+“空格”+退订回T+【签名】</div>',
        confirmButtonText: "关闭"
      });
    },
    formateDate(v) {
      return moment(v).format("YYYY-MM-DD HH:mm");
    },
    //打开日期控件
    openPicker() {
      this.$refs.dateTimePicker.open();
    },
    //日期确认
    confirmPicker(v) {
      const hour = v.getHours();
      const min = v.getMinutes();
      if (hour < 7 || hour >= 22 || (hour == 7 && min == 0)) {
        Toast("发送时间不能在免打扰时间 22点～7点");
        return;
      }
      this.sendTime = v;
    },
    //关闭日期控件
    cancelPicker(v) {
    },
    //打开门店选择
    handleClickSelectStore() {
      if (this.roleInfo.manyShopFlag!==undefined&&!this.roleInfo.manyShopFlag) {
        return;
      }
      this.$refs.StoreChoice.popupShow();
    },
    //门店选择回调
    getSelectStoreValue(value, storeName, selectAll) {
      if (selectAll) {
        this.store = [{ selectKey: "", selectName: "全部门店" }];
      } else {
        this.store = value;
      }
      this.getMemberCount();
    },
    //会员来源选择回调
    handlepickerMemberConfirm(v) {
      this.pickerMember.anchor = v;
      this.pickerMember.selected.value = this.pickerMember.data[v[0].index].id;
      this.pickerMember.selected.text = v[0].value;
      this.getMemberCount();
    },
    //性别选择回调
    handlepickerGenderConfirm(v) {
      this.pickerGender.anchor = v;
      this.pickerGender.selected.value = this.pickerGender.data[v[0].index].id;
      this.pickerGender.selected.text = v[0].value;
      this.getMemberCount();
    },
    //签名选择回调
    handlepickerSignConfirm(v) {
      this.pickerSign.anchor = v;
      this.pickerSign.selected.value = this.pickerSign.data[v[0].index].id;
      this.pickerSign.selected.text = v[0].value;
      this.contentCount(this.msgContent);
    },
    //点击请选择弹出选择项
    showPicker(ref) {
      this.$refs[ref].show();
    },
    //获取签名下拉数据
    getSignList() {
      let url = "/newapp/smsmarketing/querySignListByUseTime.do";
      this.ajax({
        type: "get",
        url: url
      })
        .then(response => {
          if (response && response.success) {
            const data = response.resultObject.filter((item) => { return item.status == 1 });
            if (data) {
              this.pickerSign.data = this.pickerSign.data.concat(
                CommonUtil.formatPickerData(
                  data,
                  "sign",
                  "signId"
                )
              );

              if (this.pickerSign.data && this.pickerSign.data.length > 0) {//默认选中第一个
                this.pickerSign.anchor = [{ index: 0 }];
                this.pickerSign.selected.value = this.pickerSign.data[0].id;
                this.pickerSign.selected.text = this.pickerSign.data[0].value;
              }

              this.contentCount(this.msgContent);
              this.loadDetails();
            }
          } else {
            this.loadDetails();
            Toast(response.msg);
          }
        })
        .catch(err => {
 
        });
    },
    //添加或者编辑短信
    addMsg() {
      if (this.loadding) {
        return;
      }
      this.loadding = true;
      let shopIdList = this.store.filter((shop) => { return shop.selectKey != "" });
      shopIdList = shopIdList.map((shop) => { return shop.selectKey });
      let memberSource = this.pickerMember.selected.value ? [this.pickerMember.selected.value] : [];
      let genderList = this.pickerGender.selected.value ? [parseInt(this.pickerGender.selected.value)] : [];
      let sendTime = this.sendTime ? this.sendTime.getTime() : new Date().getTime();
      let sendTimeType = this.switchValue ? 2 : 1;
      const params = { msgId: this.detailsParams ? this.detailsParams.msgId : "", memberSource: memberSource, genderList: genderList, signId: this.pickerSign.selected.value, sign: this.pickerSign.selected.text, shopIdList: shopIdList, msgContent: this.msgContent, sendTimeType: sendTimeType, sendTime: sendTime };
      this.ajax({
        url: "/newapp/smsmarketing/addMsgJob.do",
        type: "post",
        data: params,
        controlLoading: true
      })
        .then(res => {
          this.loadding = false;
          if (res.success) {
            Toast("提交成功");
            this.$router.push({ path: "/messageMarketing/sendRecord" });
          } else {
            Toast(res.msg);
          }
        })
        .catch((err) => {
          this.loadding = false;
        });
    },
    //提交
    submit() {
      if (this.msgContent.length === 0) {
        Toast("请输入短信内容");
        return;
      }
      if (!this.switchValue) {
        this.sendTime = new Date();
      }
      const hour = this.sendTime.getHours();
      const min = this.sendTime.getMinutes();
      if (hour < 7 || hour >= 22 || (hour == 7 && min == 0)) {
        Toast("请在7:00～22:00发送短信");
        return;
      }
      // if (!this.pickerMember.selected.value) {
      //   Toast("请选择会员来源");
      //   return;
      // }
      // if (!this.pickerGender.selected.value) {
      //   Toast("请选择性别");
      //   return;
      // }
      if (!this.pickerSign.selected.value) {
        Toast("请选择签名，如没有签名，请先创建后在进行短信发送");
        return;
      }

      //若触达人数为0时，
      //判断【会员管理】模块是否已开通？
      //• 若已开通提示“当前发送会员数为0，请选择会员后进行发送”
      //• 若未开通提示“当前商户为开通会员管理功能，请开通后再进行短信发送”，点击进入会员管理开通页面；
      if (this.memberCount == 0 && !this.isOpenMember) {
        MessageBox({
          title: '提示',
          message: '当前商户未开通会员管理功能，请开通后再进行短信发送',
          showCancelButton: true,
        }).then(action => {
          if (action == "confirm") {
            this.$router.push({ path: "/mallList/serviceProductDetails", query: { machineType: 19, close: true } });
          }
        });
        return;
      }

      if (this.memberCount == 0) {
        MessageBox({
          title: '提示',
          message: '当前发送会员数为0，请选择会员后进行发送',
        }).then(action => {
          if (action == "confirm") {
          }

        });
        return;
      }


      if (this.msgContent.length + "退订回T".length + "【】".length + this.pickerSign.selected.text.length > 70) {
        MessageBox({
          title: '提示',
          message: '当前短信内容已超过70字，为避免产生长短信费用，请再次确认短信长度',
          showCancelButton: true,
          confirmButtonText: "确认发送",
        }).then(action => {
          if (action == "confirm") {
            this.addMsg();
          }

        });
      } else {
        this.addMsg();
      }

    },
    //获取触达人数
    getMemberCount() {
      let shopIdList = this.store.filter((shop) => { return shop.selectKey != "" });
      shopIdList = shopIdList.map((shop) => { return shop.selectKey });
      let memberSource = this.pickerMember.selected.value ? [this.pickerMember.selected.value] : [];
      let genderList = this.pickerGender.selected.value ? [parseInt(this.pickerGender.selected.value)] : [];
      let params = { shopIdList: shopIdList, memberSource: memberSource, genderList: genderList };
      this.ajax({
        url: `/newapp/smsmarketing/queryPeople.do`,
        type: "post",
        data: params,
        controlLoading: false
      })
        .then(res => {
          if (res.success) {
            this.memberCount = res.resultObject;
          } else {
            Toast(res.msg);
          }
        })
        .catch((err) => {

        });
    },
    //编辑回显
    setDetails() {
      if (this.detailsParams) {
        this.memberCount = this.detailsParams.memberCount;
        this.msgContent = this.detailsParams.msgContent;
        if (this.detailsParams.sendTimeType == 2) {
          this.switchValue = true;
          this.sendTime = new Date(this.detailsParams.sendTime);
        } else {
          this.switchValue = false;
        }

        if (!this.detailsParams.tagContent) {
          return;
        }
        const tagContent = JSON.parse(this.detailsParams.tagContent);
        this.store = tagContent.shopList.map((shop) => {
          return { selectKey: shop.shopId, selectName: tagContent["shopName"] ? tagContent["shopName"] : "" }
        });

        const p1v = this.pickerMember.data.filter((item) => { return item.id === String(tagContent.memberSource[0]) });
        if (p1v && p1v.length > 0) {
          this.pickerMember.anchor = p1v;
          this.pickerMember.selected = { text: p1v[0].value, value: p1v[0].id };
        }

        const p2v = this.pickerGender.data.filter((item) => { return item.id === String(tagContent.genderList[0]) });
        if (p2v && p2v.length > 0) {
          this.pickerGender.anchor = p2v;
          this.pickerGender.selected = { text: p2v[0].value, value: p2v[0].id };
        }
        const p3v = this.pickerSign.data.filter((item) => { return item.id == this.detailsParams.signId });
        if (p3v && p3v.length > 0) {
          this.pickerSign.anchor = p3v;
          this.pickerSign.selected = { text: p3v[0].value, value: p3v[0].id };
        }
      }
    },
    //条数计算
    contentCount(msgContent) {
      const total = msgContent.length + "退订回T".length + "【】空".length + this.pickerSign.selected.text.length;
      let tip = `总计：${total}个字`;
      if (total > 70) {
        const n = Math.ceil(total / 67);
        const remainder = total - Math.floor(total / 67) * 67;
        tip = tip + `，第1条 67个字 第${n}条 ${remainder}/67个字`;
      }
      this.fieldTip = tip;
    },
    //是否订购会员管理
    getStatus() {
      //serviceCode 服务类型：9：小程序；10：会员服务
      this.ajax({
        url: "/applet/manager/queryYzProShopServiceModelByCondition.do?serviceCode=10",
        type: "get",
        controlLoading: false
      })
        .then(res => {
          if (res.success) {
            const status = res.resultObject;//小程序： 0:未开通 1:开启 2:停用 会员服务： 0:关闭 1:开启
            if (status === 1) {
              this.isOpenMember = true;
            }
          } else {
            Toast(res.msg);
          }
        })
        .catch(function (err) {

        });
    },
    //加载详情
    loadDetails() {
      if (!this.$route.query.msgId) {
        return;
      };
      this.ajax({
        url: `/newapp/smsmarketing/getMsgDetail.do?msgId=${this.$route.query.msgId}`,
        type: "get",
        controlLoading: true
      })
        .then(res => {
          if (res.success) {
            this.detailsParams = res.resultObject;
            if (res.resultObject && res.resultObject.tagContent) {
              this.setDetails();
            }
          } else {
            Toast(res.msg);
          }
        })
        .catch((err) => {

        });
    },
  },
  computed: {

  },
  created() {
    CommonUtil.getUserInfo().then(userInfo => {
      this.roleInfo = userInfo;
      if (!userInfo.manyShopFlag) {
        this.store = [{ selectKey: userInfo.yzShopId, selectName: userInfo.shopName }]
      }
      !this.$route.query.msgId && this.getMemberCount();
    });
    this.getSignList();
    this.contentCount(this.msgContent);
    this.getStatus();

  },
  watch: {
    msgContent(v) {
      this.contentCount(v);
    }
  },
  components: {
    customHeader,
    StoreChoice

  },
};
</script>
<style lang="scss" scoped>
@import "messageMarketing";
</style>
<style lang="scss" >
.date-timer-picker {
  .picker-slot {
    font-size: 0.76rem;
  }
}
.pickerZindex {
  .mask {
    background: rgba(0, 0, 0, 0.5) !important;
  }
}
</style>
